{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Collaborative Filtering Classification Example\n",
    "\n",
    "> Documentação: http://spark.apache.org/docs/1.6.2/mllib-collaborative-filtering.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Carregando e traduzindo o dado"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "data = sc.textFile(\"data/als_test.data\")\n",
    "ratings = data.map(lambda l: l.split(',')).map(lambda l: Rating( int(l[0]), int(l[1]), float(l[2]) ) )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Construindo o modelo de recomendação usando Alternating Least Squares"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "rank = 10\n",
    "numIterations = 10\n",
    "model = ALS.train(ratings, rank, numIterations)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Avaliando modelo em dados de treinamento"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "testdata = ratings.map(lambda p: (p[0], p[1]))                                # Mapeando apenas para (usuário, item)\n",
    "predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))  # Predizendo a avaliações para usuários e items\n",
    "ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions) # Juntando as predições com as avaliações reais\n",
    "MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean()              # Computando Erro Quadrático Médio\n",
    "print \"Mean Squared Error = \" + str(MSE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Pyspark (Py 2)",
   "language": "",
   "name": "pyspark"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
